package md.rdcrng.cvs;

import java.lang.annotation.Annotation;
import javax.enterprise.context.ContextNotActiveException;
import javax.enterprise.context.spi.Context;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;

/**
 <p/>
 @author Radu Creanga <rdcrng@gmail.com>
 */
class ViewContext implements Context {

    private final ViewStorage viewStorage;

    public ViewContext(ViewStorage viewStorage) {
        this.viewStorage = viewStorage;
    }

    @Override
    public Class<? extends Annotation> getScope() {
        return ViewScoped.class;
    }

    @Override
    public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
        this.checkActive();
        return this.printThenReturn(this.viewStorage.create(contextual, creationalContext));
    }

    @Override
    public <T> T get(Contextual<T> contextual) {
        this.checkActive();
        return this.printThenReturn(this.viewStorage.get(contextual));
    }

    private <T> T printThenReturn(T t) {
        System.err.println(t);
        return t;
    }

    @Override
    public boolean isActive() {
        try {
            return Faces.getViewRoot() != null;
        } catch (NullPointerException e) {
            return false;
        }
    }

    private void checkActive() throws ContextNotActiveException {
        try {
            if (Faces.getViewRoot() == null) {
                throw new ContextNotActiveException();
            }
        } catch (NullPointerException e) {
            throw new ContextNotActiveException(e);
        }
    }

}
